package javaBeam.web;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javaBeam.domain.UserBean;
import javaBeam.util.DBUtil;

import java.io.IOException;

@WebServlet(name = "ControllerLoginServlet",urlPatterns = "/ControllerLoginServlet")
public class ControllerLoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-type", "text/html;charser=GBK");
        resp.setCharacterEncoding("GBK");

        String name = req.getParameter("name");
        String passwrod = req.getParameter("password");

        UserBean user = new UserBean();
        user.setName(name);
        user.setPassword(passwrod);

        boolean b = DBUtil.getInstance().checkSata(user);

        if (b){
            UserBean userBean = DBUtil.getInstance().getUser(name);
            resp.getWriter().print("恭喜你登录成功，3秒后自动跳转");
            req.getSession().setAttribute("userBean",userBean);
            resp.setHeader("refresh","3;url=loginSuccess.jsp");
        }else {
            req.setAttribute("DBMes","用户名或密码错误");
            req.getRequestDispatcher("/index.jsp")
                    .forward(req,resp);
            return;
        }
    }
}
